home *** CD-ROM | disk | FTP | other *** search
/ Die Ultimative Software-P…i Collection 1996 & 1997 / Die Ultimative Software-Pakete CD-ROM fur Atari Collection 1996 & 1997.iso / g / gnu_c / info.lzh / INFO / CPP_INFO.1 < prev    next >
Encoding:
GNU Info File  |  1993-10-21  |  50.7 KB  |  1,232 lines

  1. This is Info file cpp.info, produced by Makeinfo-1.49 from the input
  2. file cpp.texi.
  3.  
  4.    This file documents the GNU C Preprocessor.
  5.  
  6.    Copyright 1987, 1989, 1991, 1992, 1993 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the entire resulting derived work is distributed under the terms
  15. of a permission notice identical to this one.
  16.  
  17.    Permission is granted to copy and distribute translations of this
  18. manual into another language, under the above conditions for modified
  19. versions.
  20.  
  21. File: cpp.info,  Node: Top,  Next: Global Actions,  Up: (DIR)
  22.  
  23. The C Preprocessor
  24. ******************
  25.  
  26.    The C preprocessor is a "macro processor" that is used automatically
  27. by the C compiler to transform your program before actual compilation. 
  28. It is called a macro processor because it allows you to define "macros",
  29. which are brief abbreviations for longer constructs.
  30.  
  31.    The C preprocessor provides four separate facilities that you can
  32. use as you see fit:
  33.  
  34.    * Inclusion of header files.  These are files of declarations that
  35.      can be substituted into your program.
  36.  
  37.    * Macro expansion.  You can define "macros", which are abbreviations
  38.      for arbitrary fragments of C code, and then the C preprocessor will
  39.      replace the macros with their definitions throughout the program.
  40.  
  41.    * Conditional compilation.  Using special preprocessor commands, you
  42.      can include or exclude parts of the program according to various
  43.      conditions.
  44.  
  45.    * Line control.  If you use a program to combine or rearrange source
  46.      files into an intermediate file which is then compiled, you can
  47.      use line control to inform the compiler of where each source line
  48.      originally came from.
  49.  
  50.    C preprocessors vary in some details.  This manual discusses the GNU
  51. C preprocessor, the C Compatible Compiler Preprocessor.  The GNU C
  52. preprocessor provides a superset of the features of ANSI Standard C.
  53.  
  54.    ANSI Standard C requires the rejection of many harmless constructs
  55. commonly used by today's C programs.  Such incompatibility would be
  56. inconvenient for users, so the GNU C preprocessor is configured to
  57. accept these constructs by default.  Strictly speaking, to get ANSI
  58. Standard C, you must use the options `-trigraphs', `-undef' and
  59. `-pedantic', but in practice the consequences of having strict ANSI
  60. Standard C make it undesirable to do this.  *Note Invocation::.
  61.  
  62. * Menu:
  63.  
  64. * Global Actions::    Actions made uniformly on all input files.
  65. * Commands::          General syntax of preprocessor commands.
  66. * Header Files::      How and why to use header files.
  67. * Macros::            How and why to use macros.
  68. * Conditionals::      How and why to use conditionals.
  69. * Combining Sources:: Use of line control when you combine source files.
  70. * Other Commands::    Miscellaneous preprocessor commands.
  71. * Output::            Format of output from the C preprocessor.
  72. * Invocation::        How to invoke the preprocessor; command options.
  73. * Concept Index::     Index of concepts and terms.
  74. * Index::             Index of commands, predefined macros and options.
  75.  
  76. File: cpp.info,  Node: Global Actions,  Next: Commands,  Prev: Top,  Up: Top
  77.  
  78. Transformations Made Globally
  79. =============================
  80.  
  81.    Most C preprocessor features are inactive unless you give specific
  82. commands to request their use.  (Preprocessor commands are lines
  83. starting with `#'; *note Commands::.).  But there are three
  84. transformations that the preprocessor always makes on all the input it
  85. receives, even in the absence of commands.
  86.  
  87.    * All C comments are replaced with single spaces.
  88.  
  89.    * Backslash-Newline sequences are deleted, no matter where.  This
  90.      feature allows you to break long lines for cosmetic purposes
  91.      without changing their meaning.
  92.  
  93.    * Predefined macro names are replaced with their expansions (*note
  94.      Predefined::.).
  95.  
  96.    The first two transformations are done *before* nearly all other
  97. parsing and before preprocessor commands are recognized.  Thus, for
  98. example, you can split a line cosmetically with Backslash-Newline
  99. anywhere (except when trigraphs are in use; see below).
  100.  
  101.      /*
  102.      */ # /*
  103.      */ defi\
  104.      ne FO\
  105.      O 10\
  106.      20
  107.  
  108. is equivalent into `#define FOO 1020'.  You can split even an escape
  109. sequence with Backslash-Newline.  For example, you can split `"foo\bar"'
  110. between the `\' and the `b' to get
  111.  
  112.      "foo\\
  113.      bar"
  114.  
  115. This behavior is unclean: in all other contexts, a Backslash can be
  116. inserted in a string constant as an ordinary character by writing a
  117. double Backslash, and this creates an exception.  But the ANSI C
  118. standard requires it.  (Strict ANSI C does not allow Newlines in string
  119. constants, so they do not consider this a problem.)
  120.  
  121.    But there are a few exceptions to all three transformations.
  122.  
  123.    * C comments and predefined macro names are not recognized inside a
  124.      `#include' command in which the file name is delimited with `<'
  125.      and `>'.
  126.  
  127.    * C comments and predefined macro names are never recognized within a
  128.      character or string constant.  (Strictly speaking, this is the
  129.      rule, not an exception, but it is worth noting here anyway.)
  130.  
  131.    * Backslash-Newline may not safely be used within an ANSI "trigraph".
  132.      Trigraphs are converted before Backslash-Newline is deleted.  If
  133.      you write what looks like a trigraph with a Backslash-Newline
  134.      inside, the Backslash-Newline is deleted as usual, but it is then
  135.      too late to recognize the trigraph.
  136.  
  137.      This exception is relevant only if you use the `-trigraphs' option
  138.      to enable trigraph processing.  *Note Invocation::.
  139.  
  140. File: cpp.info,  Node: Commands,  Next: Header Files,  Prev: Global Actions,  Up: Top
  141.  
  142. Preprocessor Commands
  143. =====================
  144.  
  145.    Most preprocessor features are active only if you use preprocessor
  146. commands to request their use.
  147.  
  148.    Preprocessor commands are lines in your program that start with `#'.
  149. The `#' is followed by an identifier that is the "command name". For
  150. example, `#define' is the command that defines a macro. Whitespace is
  151. also allowed before and after the `#'.
  152.  
  153.    The set of valid command names is fixed.  Programs cannot define new
  154. preprocessor commands.
  155.  
  156.    Some command names require arguments; these make up the rest of the
  157. command line and must be separated from the command name by whitespace.
  158.  For example, `#define' must be followed by a macro name and the
  159. intended expansion of the macro.
  160.  
  161.    A preprocessor command cannot be more than one line in normal
  162. circumstances. It may be split cosmetically with Backslash-Newline, but
  163. that has no effect on its meaning.  Comments containing Newlines can
  164. also divide the command into multiple lines, but the comments are
  165. changed to Spaces before the command is interpreted.  The only way a
  166. significant Newline can occur in a preprocessor command is within a
  167. string constant or character constant.  Note that most C compilers that
  168. might be applied to the output from the preprocessor do not accept
  169. string or character constants containing Newlines.
  170.  
  171.    The `#' and the command name cannot come from a macro expansion.  For
  172. example, if `foo' is defined as a macro expanding to `define', that
  173. does not make `#foo' a valid preprocessor command.
  174.  
  175. File: cpp.info,  Node: Header Files,  Next: Macros,  Prev: Commands,  Up: Top
  176.  
  177. Header Files
  178. ============
  179.  
  180.    A header file is a file containing C declarations and macro
  181. definitions (*note Macros::.) to be shared between several source
  182. files.  You request the use of a header file in your program with the C
  183. preprocessor command `#include'.
  184.  
  185. * Menu:
  186.  
  187. * Header Uses::         What header files are used for.
  188. * Include Syntax::      How to write `#include' commands.
  189. * Include Operation::   What `#include' does.
  190. * Once-Only::        Preventing multiple inclusion of one header file.
  191. * Inheritance::         Including one header file in another header file.
  192.  
  193. File: cpp.info,  Node: Header Uses,  Next: Include Syntax,  Prev: Header Files,  Up: Header Files
  194.  
  195. Uses of Header Files
  196. --------------------
  197.  
  198.    Header files serve two kinds of purposes.
  199.  
  200.    * System header files declare the interfaces to parts of the
  201.      operating system.  You include them in your program to supply the
  202.      definitions and declarations you need to invoke system calls and
  203.      libraries.
  204.  
  205.    * Your own header files contain declarations for interfaces between
  206.      the source files of your program.  Each time you have a group of
  207.      related declarations and macro definitions all or most of which
  208.      are needed in several different source files, it is a good idea to
  209.      create a header file for them.
  210.  
  211.    Including a header file produces the same results in C compilation as
  212. copying the header file into each source file that needs it.  But such
  213. copying would be time-consuming and error-prone.  With a header file,
  214. the related declarations appear in only one place.  If they need to be
  215. changed, they can be changed in one place, and programs that include
  216. the header file will automatically use the new version when next
  217. recompiled.  The header file eliminates the labor of finding and
  218. changing all the copies as well as the risk that a failure to find one
  219. copy will result in inconsistencies within a program.
  220.  
  221.    The usual convention is to give header files names that end with
  222. `.h'.
  223.  
  224. File: cpp.info,  Node: Include Syntax,  Next: Include Operation,  Prev: Header Uses,  Up: Header Files
  225.  
  226. The `#include' Command
  227. ----------------------
  228.  
  229.    Both user and system header files are included using the preprocessor
  230. command `#include'.  It has three variants:
  231.  
  232. `#include <FILE>'
  233.      This variant is used for system header files.  It searches for a
  234.      file named FILE in a list of directories specified by you, then in
  235.      a standard list of system directories.  You specify directories to
  236.      search for header files with the command option `-I' (*note
  237.      Invocation::.).  The option `-nostdinc' inhibits searching the
  238.      standard system directories; in this case only the directories you
  239.      specify are searched.
  240.  
  241.      The parsing of this form of `#include' is slightly special because
  242.      comments are not recognized within the `<...>'. Thus, in `#include
  243.      <x/*y>' the `/*' does not start a comment and the command
  244.      specifies inclusion of a system header file named `x/*y'.  Of
  245.      course, a header file with such a name is unlikely to exist on
  246.      Unix, where shell wildcard features would make it hard to
  247.      manipulate.
  248.  
  249.      The argument FILE may not contain a `>' character.  It may,
  250.      however, contain a `<' character.
  251.  
  252. `#include "FILE"'
  253.      This variant is used for header files of your own program.  It
  254.      searches for a file named FILE first in the current directory,
  255.      then in the same directories used for system header files.  The
  256.      current directory is the directory of the current input file.  It
  257.      is tried first because it is presumed to be the location of the
  258.      files that the current input file refers to.  (If the `-I-' option
  259.      is used, the special treatment of the current directory is
  260.      inhibited.)
  261.  
  262.      The argument FILE may not contain `"' characters.  If backslashes
  263.      occur within FILE, they are considered ordinary text characters,
  264.      not escape characters.  None of the character escape sequences
  265.      appropriate to string constants in C are processed.  Thus,
  266.      `#include "x\n\\y"' specifies a filename containing three
  267.      backslashes.  It is not clear why this behavior is ever useful, but
  268.      the ANSI standard specifies it.
  269.  
  270. `#include ANYTHING ELSE'
  271.      This variant is called a "computed #include".  Any `#include'
  272.      command whose argument does not fit the above two forms is a
  273.      computed include.  The text ANYTHING ELSE is checked for macro
  274.      calls, which are expanded (*note Macros::.).  When this is done,
  275.      the result must fit one of the above two variants--in particular,
  276.      the expanded text must in the end be surrounded by either quotes
  277.      or angle braces.
  278.  
  279.      This feature allows you to define a macro which controls the file
  280.      name to be used at a later point in the program.  One application
  281.      of this is to allow a site-configuration file for your program to
  282.      specify the names of the system include files to be used.  This
  283.      can help in porting the program to various operating systems in
  284.      which the necessary system header files are found in different
  285.      places.
  286.  
  287. File: cpp.info,  Node: Include Operation,  Next: Once-Only,  Prev: Include Syntax,  Up: Header Files
  288.  
  289. How `#include' Works
  290. --------------------
  291.  
  292.    The `#include' command works by directing the C preprocessor to scan
  293. the specified file as input before continuing with the rest of the
  294. current file.  The output from the preprocessor contains the output
  295. already generated, followed by the output resulting from the included
  296. file, followed by the output that comes from the text after the
  297. `#include' command.  For example, given two files as follows:
  298.  
  299.      /* File program.c */
  300.      int x;
  301.      #include "header.h"
  302.      
  303.      main ()
  304.      {
  305.        printf (test ());
  306.      }
  307.      
  308.      
  309.      /* File header.h */
  310.      char *test ();
  311.  
  312. the output generated by the C preprocessor for `program.c' as input
  313. would be
  314.  
  315.      int x;
  316.      char *test ();
  317.      
  318.      main ()
  319.      {
  320.        printf (test ());
  321.      }
  322.  
  323.    Included files are not limited to declarations and macro
  324. definitions; those are merely the typical uses.  Any fragment of a C
  325. program can be included from another file.  The include file could even
  326. contain the beginning of a statement that is concluded in the
  327. containing file, or the end of a statement that was started in the
  328. including file.  However, a comment or a string or character constant
  329. may not start in the included file and finish in the including file. 
  330. An unterminated comment, string constant or character constant in an
  331. included file is considered to end (with an error message) at the end
  332. of the file.
  333.  
  334.    The line following the `#include' command is always treated as a
  335. separate line by the C preprocessor even if the included file lacks a
  336. final newline.
  337.  
  338. File: cpp.info,  Node: Once-Only,  Next: Inheritance,  Prev: Include Operation,  Up: Header Files
  339.  
  340. Once-Only Include Files
  341. -----------------------
  342.  
  343.    Very often, one header file includes another.  It can easily result
  344. that a certain header file is included more than once.  This may lead
  345. to errors, if the header file defines structure types or typedefs, and
  346. is certainly wasteful.  Therefore, we often wish to prevent multiple
  347. inclusion of a header file.
  348.  
  349.    The standard way to do this is to enclose the entire real contents
  350. of the file in a conditional, like this:
  351.  
  352.      #ifndef __FILE_FOO_SEEN__
  353.      #define __FILE_FOO_SEEN__
  354.      
  355.      THE ENTIRE FILE
  356.      
  357.      #endif /* __FILE_FOO_SEEN__ */
  358.  
  359.    The macro `__FILE_FOO_SEEN__' indicates that the file has been
  360. included once already; its name should begin with `__' to avoid
  361. conflicts with user programs, and it should contain the name of the file
  362. and some additional text, to avoid conflicts with other header files.
  363.  
  364.    The GNU C preprocessor is programmed to notice when a header file
  365. uses this particular construct and handle it efficiently.  If a header
  366. file is contained entirely in a `#ifndef' conditional, then it records
  367. that fact.  If a subsequent `#include' specifies the same file, and the
  368. macro in the `#ifndef' is already defined, then the file is entirely
  369. skipped, without even reading it.
  370.  
  371.    There is also an explicit command to tell the preprocessor that it
  372. need not include a file more than once.  This is called `#pragma once',
  373. and was used *in addition to* the `#ifndef' conditional around the
  374. contents of the header file.  `#pragma once' is now obsolete and should
  375. not be used at all.
  376.  
  377.    In the Objective C language, there is a variant of `#include' called
  378. `#import' which includes a file, but does so at most once. If you use
  379. `#import' *instead of* `#include', then you don't need the conditionals
  380. inside the header file to prevent multiple execution of the contents.
  381.  
  382.    `#import' is obsolete because it is not a well-designed feature. It
  383. requires the users of a header file--the applications programmers--to
  384. know that a certain header file should only be included once.  It is
  385. much better for the header file's implementor to write the file so that
  386. users don't need to know this.  Using `#ifndef' accomplishes this goal.
  387.  
  388. File: cpp.info,  Node: Inheritance,  Prev: Once-Only,  Up: Header Files
  389.  
  390. Inheritance and Header Files
  391. ============================
  392.  
  393.    "Inheritance" is what happens when one object or file derives some
  394. of its contents by virtual copying from another object or file.  In the
  395. case of C header files, inheritance means that one header file includes
  396. another header file and then replaces or adds something.
  397.  
  398.    If the inheriting header file and the base header file have different
  399. names, then inheritance is straightforward: simply write `#include
  400. "BASE"' in the inheriting file.
  401.  
  402.    Sometimes it is necessary to give the inheriting file the same name
  403. as the base file.  This is less straightforward.
  404.  
  405.    For example, suppose an application program uses the system header
  406. file `sys/signal.h', but the version of `/usr/include/sys/signal.h' on
  407. a particular system doesn't do what the application program expects. It
  408. might be convenient to define a "local" version, perhaps under the name
  409. `/usr/local/include/sys/signal.h', to override or add to the one
  410. supplied by the system.
  411.  
  412.    You can do this by using the option `-I.' for compilation, and
  413. writing a file `sys/signal.h' that does what the application program
  414. expects.  But making this file include the standard `sys/signal.h' is
  415. not so easy--writing `#include <sys/signal.h>' in that file doesn't
  416. work, because it includes your own version of the file, not the
  417. standard system version.  Used in that file itself, this leads to an
  418. infinite recursion and a fatal error in compilation.
  419.  
  420.    `#include </usr/include/sys/signal.h>' would find the proper file,
  421. but that is not clean, since it makes an assumption about where the
  422. system header file is found.  This is bad for maintenance, since it
  423. means that any change in where the system's header files are kept
  424. requires a change somewhere else.
  425.  
  426.    The clean way to solve this problem is to use `#include_next', which
  427. means, "Include the *next* file with this name."  This command works
  428. like `#include' except in searching for the specified file: it starts
  429. searching the list of header file directories *after* the directory in
  430. which the current file was found.
  431.  
  432.    Suppose you specify `-I /usr/local/include', and the list of
  433. directories to search also includes `/usr/include'; and suppose that
  434. both directories contain a file named `sys/signal.h'.  Ordinary
  435. `#include <sys/signal.h>' finds the file under `/usr/local/include'. 
  436. If that file contains `#include_next <sys/signal.h>', it starts
  437. searching after that directory, and finds the file in `/usr/include'.
  438.  
  439. File: cpp.info,  Node: Macros,  Next: Conditionals,  Prev: Header Files,  Up: Top
  440.  
  441. Macros
  442. ======
  443.  
  444.    A macro is a sort of abbreviation which you can define once and then
  445. use later.  There are many complicated features associated with macros
  446. in the C preprocessor.
  447.  
  448. * Menu:
  449.  
  450. * Simple Macros::    Macros that always expand the same way.
  451. * Argument Macros::  Macros that accept arguments that are substituted
  452.                        into the macro expansion.
  453. * Predefined::       Predefined macros that are always available.
  454. * Stringification::  Macro arguments converted into string constants.
  455. * Concatenation::    Building tokens from parts taken from macro arguments.
  456. * Undefining::       Cancelling a macro's definition.
  457. * Redefining::       Changing a macro's definition.
  458. * Macro Pitfalls::   Macros can confuse the unwary.  Here we explain
  459.                        several common problems and strange features.
  460.  
  461. File: cpp.info,  Node: Simple Macros,  Next: Argument Macros,  Prev: Macros,  Up: Macros
  462.  
  463. Simple Macros
  464. -------------
  465.  
  466.    A "simple macro" is a kind of abbreviation.  It is a name which
  467. stands for a fragment of code.  Some people refer to these as "manifest
  468. constants".
  469.  
  470.    Before you can use a macro, you must "define" it explicitly with the
  471. `#define' command.  `#define' is followed by the name of the macro and
  472. then the code it should be an abbreviation for.  For example,
  473.  
  474.      #define BUFFER_SIZE 1020
  475.  
  476. defines a macro named `BUFFER_SIZE' as an abbreviation for the text
  477. `1020'.  Therefore, if somewhere after this `#define' command there
  478. comes a C statement of the form
  479.  
  480.      foo = (char *) xmalloc (BUFFER_SIZE);
  481.  
  482. then the C preprocessor will recognize and "expand" the macro
  483. `BUFFER_SIZE', resulting in
  484.  
  485.      foo = (char *) xmalloc (1020);
  486.  
  487. the definition must be a single line; however, it may not end in the
  488. middle of a multi-line string constant or character constant.
  489.  
  490.    The use of all upper case for macro names is a standard convention.
  491. Programs are easier to read when it is possible to tell at a glance
  492. which names are macros.
  493.  
  494.    Normally, a macro definition must be a single line, like all C
  495. preprocessor commands.  (You can split a long macro definition
  496. cosmetically with Backslash-Newline.)  There is one exception: Newlines
  497. can be included in the macro definition if within a string or character
  498. constant.  By the same token, it is not possible for a macro definition
  499. to contain an unbalanced quote character; the definition automatically
  500. extends to include the matching quote character that ends the string or
  501. character constant. Comments within a macro definition may contain
  502. Newlines, which make no difference since the comments are entirely
  503. replaced with Spaces regardless of their contents.
  504.  
  505.    Aside from the above, there is no restriction on what can go in a
  506. macro body.  Parentheses need not balance.  The body need not resemble
  507. valid C code.  (Of course, you might get error messages from the C
  508. compiler when you use the macro.)
  509.  
  510.    The C preprocessor scans your program sequentially, so macro
  511. definitions take effect at the place you write them.  Therefore, the
  512. following input to the C preprocessor
  513.  
  514.      foo = X;
  515.      #define X 4
  516.      bar = X;
  517.  
  518. produces as output
  519.  
  520.      foo = X;
  521.      
  522.      bar = 4;
  523.  
  524.    After the preprocessor expands a macro name, the macro's definition
  525. body is appended to the front of the remaining input, and the check for
  526. macro calls continues.  Therefore, the macro body can contain calls to
  527. other macros. For example, after
  528.  
  529.      #define BUFSIZE 1020
  530.      #define TABLESIZE BUFSIZE
  531.  
  532. the name `TABLESIZE' when used in the program would go through two
  533. stages of expansion, resulting ultimately in `1020'.
  534.  
  535.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  536. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  537. this case, `BUFSIZE'--and does not check to see whether it too is the
  538. name of a macro.  It's only when you *use* `TABLESIZE' that the result
  539. of its expansion is checked for more macro names. *Note Cascaded
  540. Macros::.
  541.  
  542. File: cpp.info,  Node: Argument Macros,  Next: Predefined,  Prev: Simple Macros,  Up: Macros
  543.  
  544. Macros with Arguments
  545. ---------------------
  546.  
  547.    A simple macro always stands for exactly the same text, each time it
  548. is used.  Macros can be more flexible when they accept "arguments".
  549. Arguments are fragments of code that you supply each time the macro is
  550. used.  These fragments are included in the expansion of the macro
  551. according to the directions in the macro definition.
  552.  
  553.    To define a macro that uses arguments, you write a `#define' command
  554. with a list of "argument names" in parentheses after the name of the
  555. macro.  The argument names may be any valid C identifiers, separated by
  556. commas and optionally whitespace.  The open-parenthesis must follow the
  557. macro name immediately, with no space in between.
  558.  
  559.    For example, here is a macro that computes the minimum of two numeric
  560. values, as it is defined in many C programs:
  561.  
  562.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  563.  
  564. (This is not the best way to define a "minimum" macro in GNU C. *Note
  565. Side Effects::, for more information.)
  566.  
  567.    To use a macro that expects arguments, you write the name of the
  568. macro followed by a list of "actual arguments" in parentheses,
  569. separated by commas.  The number of actual arguments you give must
  570. match the number of arguments the macro expects.   Examples of use of
  571. the macro `min' include `min (1, 2)' and `min (x + 28, *p)'.
  572.  
  573.    The expansion text of the macro depends on the arguments you use.
  574. Each of the argument names of the macro is replaced, throughout the
  575. macro definition, with the corresponding actual argument.  Using the
  576. same macro `min' defined above, `min (1, 2)' expands into
  577.  
  578.      ((1) < (2) ? (1) : (2))
  579.  
  580. where `1' has been substituted for `X' and `2' for `Y'.
  581.  
  582.    Likewise, `min (x + 28, *p)' expands into
  583.  
  584.      ((x + 28) < (*p) ? (x + 28) : (*p))
  585.  
  586.    Parentheses in the actual arguments must balance; a comma within
  587. parentheses does not end an argument.  However, there is no requirement
  588. for brackets or braces to balance, and they do not prevent a comma from
  589. separating arguments.  Thus,
  590.  
  591.      macro (array[x = y, x + 1])
  592.  
  593. passes two arguments to `macro': `array[x = y' and `x + 1]'.  If you
  594. want to supply `array[x = y, x + 1]' as an argument, you must write it
  595. as `array[(x = y, x + 1)]', which is equivalent C code.
  596.  
  597.    After the actual arguments are substituted into the macro body, the
  598. entire result is appended to the front of the remaining input, and the
  599. check for macro calls continues.  Therefore, the actual arguments can
  600. contain calls to other macros, either with or without arguments, or
  601. even to the same macro.  The macro body can also contain calls to other
  602. macros.  For example, `min (min (a, b), c)' expands into this text:
  603.  
  604.      ((((a) < (b) ? (a) : (b))) < (c)
  605.       ? (((a) < (b) ? (a) : (b)))
  606.       : (c))
  607.  
  608. (Line breaks shown here for clarity would not actually be generated.)
  609.  
  610.    If a macro `foo' takes one argument, and you want to supply an empty
  611. argument, you must write at least some whitespace between the
  612. parentheses, like this: `foo ( )'.  Just `foo ()' is providing no
  613. arguments, which is an error if `foo' expects an argument.  But `foo0
  614. ()' is the correct way to call a macro defined to take zero arguments,
  615. like this:
  616.  
  617.      #define foo0() ...
  618.  
  619.    If you use the macro name followed by something other than an
  620. open-parenthesis (after ignoring any spaces, tabs and comments that
  621. follow), it is not a call to the macro, and the preprocessor does not
  622. change what you have written.  Therefore, it is possible for the same
  623. name to be a variable or function in your program as well as a macro,
  624. and you can choose in each instance whether to refer to the macro (if
  625. an actual argument list follows) or the variable or function (if an
  626. argument list does not follow).
  627.  
  628.    Such dual use of one name could be confusing and should be avoided
  629. except when the two meanings are effectively synonymous: that is, when
  630. the name is both a macro and a function and the two have similar
  631. effects.  You can think of the name simply as a function; use of the
  632. name for purposes other than calling it (such as, to take the address)
  633. will refer to the function, while calls will expand the macro and
  634. generate better but equivalent code.  For example, you can use a
  635. function named `min' in the same source file that defines the macro. 
  636. If you write `&min' with no argument list, you refer to the function. 
  637. If you write `min (x, bb)', with an argument list, the macro is
  638. expanded.  If you write `(min) (a, bb)', where the name `min' is not
  639. followed by an open-parenthesis, the macro is not expanded, so you wind
  640. up with a call to the function `min'.
  641.  
  642.    You may not define the same name as both a simple macro and a macro
  643. with arguments.
  644.  
  645.    In the definition of a macro with arguments, the list of argument
  646. names must follow the macro name immediately with no space in between. 
  647. If there is a space after the macro name, the macro is defined as
  648. taking no arguments, and all the rest of the line is taken to be the
  649. expansion.  The reason for this is that it is often useful to define a
  650. macro that takes no arguments and whose definition begins with an
  651. identifier in parentheses. This rule about spaces makes it possible for
  652. you to do either this:
  653.  
  654.      #define FOO(x) - 1 / (x)
  655.  
  656. (which defines `FOO' to take an argument and expand into minus the
  657. reciprocal of that argument) or this:
  658.  
  659.      #define BAR (x) - 1 / (x)
  660.  
  661. (which defines `BAR' to take no argument and always expand into `(x) -
  662. 1 / (x)').
  663.  
  664.    Note that the *uses* of a macro with arguments can have spaces before
  665. the left parenthesis; it's the *definition* where it matters whether
  666. there is a space.
  667.  
  668. File: cpp.info,  Node: Predefined,  Next: Stringification,  Prev: Argument Macros,  Up: Macros
  669.  
  670. Predefined Macros
  671. -----------------
  672.  
  673.    Several simple macros are predefined.  You can use them without
  674. giving definitions for them.  They fall into two classes: standard
  675. macros and system-specific macros.
  676.  
  677. * Menu:
  678.  
  679. * Standard Predefined::     Standard predefined macros.
  680. * Nonstandard Predefined::  Nonstandard predefined macros.
  681.  
  682. File: cpp.info,  Node: Standard Predefined,  Next: Nonstandard Predefined,  Prev: Predefined,  Up: Predefined
  683.  
  684. Standard Predefined Macros
  685. ..........................
  686.  
  687.    The standard predefined macros are available with the same meanings
  688. regardless of the machine or operating system on which you are using
  689. GNU C. Their names all start and end with double underscores.  Those
  690. preceding `__GNUC__' in this table are standardized by ANSI C; the rest
  691. are GNU C extensions.
  692.  
  693. `__FILE__'
  694.      This macro expands to the name of the current input file, in the
  695.      form of a C string constant.  The precise name returned is the one
  696.      that was specified in `#include' or as the input file name
  697.      argument.
  698.  
  699. `__LINE__'
  700.      This macro expands to the current input line number, in the form
  701.      of a decimal integer constant.  While we call it a predefined
  702.      macro, it's a pretty strange macro, since its "definition" changes
  703.      with each new line of source code.
  704.  
  705.      This and `__FILE__' are useful in generating an error message to
  706.      report an inconsistency detected by the program; the message can
  707.      state the source line at which the inconsistency was detected. 
  708.      For example,
  709.  
  710.           fprintf (stderr, "Internal error: "
  711.                    "negative string length "
  712.                            "%d at %s, line %d.",
  713.                    length, __FILE__, __LINE__);
  714.  
  715.      A `#include' command changes the expansions of `__FILE__' and
  716.      `__LINE__' to correspond to the included file.  At the end of that
  717.      file, when processing resumes on the input file that contained the
  718.      `#include' command, the expansions of `__FILE__' and `__LINE__'
  719.      revert to the values they had before the `#include' (but
  720.      `__LINE__' is then incremented by one as processing moves to the
  721.      line after the `#include').
  722.  
  723.      The expansions of both `__FILE__' and `__LINE__' are altered if a
  724.      `#line' command is used.  *Note Combining Sources::.
  725.  
  726. `__INCLUDE_LEVEL__'
  727.      This macro expands to a decimal integer constant that represents
  728.      the depth of nesting in include files.  The value of this macro is
  729.      incremented on every `#include' command and decremented at every
  730.      end of file.
  731.  
  732. `__DATE__'
  733.      This macro expands to a string constant that describes the date on
  734.      which the preprocessor is being run.  The string constant contains
  735.      eleven characters and looks like `"Jan 29 1987"' or `"Apr 1 1905"'.
  736.  
  737. `__TIME__'
  738.      This macro expands to a string constant that describes the time at
  739.      which the preprocessor is being run.  The string constant contains
  740.      eight characters and looks like `"23:59:01"'.
  741.  
  742. `__STDC__'
  743.      This macro expands to the constant 1, to signify that this is ANSI
  744.      Standard C.  (Whether that is actually true depends on what C
  745.      compiler will operate on the output from the preprocessor.)
  746.  
  747. `__GNUC__'
  748.      This macro is defined if and only if this is GNU C.  This macro is
  749.      defined only when the entire GNU C compiler is in use; if you
  750.      invoke the preprocessor directly, `__GNUC__' is undefined.
  751.  
  752. `__GNUG__'
  753.      The GNU C compiler defines this when the compilation language is
  754.      C++; use `__GNUG__' to distinguish between GNU C and GNU C++.
  755.  
  756. `__cplusplus'
  757.      The draft ANSI standard for C++ used to require predefining this
  758.      variable.  Though it is no longer required, GNU C++ continues to
  759.      define it, as do other popular C++ compilers.  You can use
  760.      `__cplusplus' to test whether a header is compiled by a C compiler
  761.      or a C++ compiler.
  762.  
  763. `__STRICT_ANSI__'
  764.      This macro is defined if and only if the `-ansi' switch was
  765.      specified when GNU C was invoked.  Its definition is the null
  766.      string. This macro exists primarily to direct certain GNU header
  767.      files not to define certain traditional Unix constructs which are
  768.      incompatible with ANSI C.
  769.  
  770. `__BASE_FILE__'
  771.      This macro expands to the name of the main input file, in the form
  772.      of a C string constant.  This is the source file that was specified
  773.      as an argument when the C compiler was invoked.
  774.  
  775. `__VERSION__'
  776.      This macro expands to a string which describes the version number
  777.      of GNU C.  The string is normally a sequence of decimal numbers
  778.      separated by periods, such as `"1.18"'.  The only reasonable use
  779.      of this macro is to incorporate it into a string constant.
  780.  
  781. `__OPTIMIZE__'
  782.      This macro is defined in optimizing compilations.  It causes
  783.      certain GNU header files to define alternative macro definitions
  784.      for some system library functions.  It is unwise to refer to or
  785.      test the definition of this macro unless you make very sure that
  786.      programs will execute with the same effect regardless.
  787.  
  788. `__CHAR_UNSIGNED__'
  789.      This macro is defined if and only if the data type `char' is
  790.      unsigned on the target machine.  It exists to cause the standard
  791.      header file `limit.h' to work correctly.  It is bad practice to
  792.      refer to this macro yourself; instead, refer to the standard
  793.      macros defined in `limit.h'.  The preprocessor uses this macro to
  794.      determine whether or not to sign-extend large character constants
  795.      written in octal; see *Note The `#if' Command: #if Command.
  796.  
  797. File: cpp.info,  Node: Nonstandard Predefined,  Prev: Standard Predefined,  Up: Predefined
  798.  
  799. Nonstandard Predefined Macros
  800. .............................
  801.  
  802.    The C preprocessor normally has several predefined macros that vary
  803. between machines because their purpose is to indicate what type of
  804. system and machine is in use.  This manual, being for all systems and
  805. machines, cannot tell you exactly what their names are; instead, we
  806. offer a list of some typical ones.  You can use `cpp -dM' to see the
  807. values of predefined macros; *note Invocation::..
  808.  
  809.    Some nonstandard predefined macros describe the operating system in
  810. use, with more or less specificity.  For example,
  811.  
  812. `unix'
  813.      `unix' is normally predefined on all Unix systems.
  814.  
  815. `BSD'
  816.      `BSD' is predefined on recent versions of Berkeley Unix (perhaps
  817.      only in version 4.3).
  818.  
  819.    Other nonstandard predefined macros describe the kind of CPU, with
  820. more or less specificity.  For example,
  821.  
  822. `vax'
  823.      `vax' is predefined on Vax computers.
  824.  
  825. `mc68000'
  826.      `mc68000' is predefined on most computers whose CPU is a Motorola
  827.      68000, 68010 or 68020.
  828.  
  829. `m68k'
  830.      `m68k' is also predefined on most computers whose CPU is a 68000,
  831.      68010 or 68020; however, some makers use `mc68000' and some use
  832.      `m68k'.  Some predefine both names.  What happens in GNU C depends
  833.      on the system you are using it on.
  834.  
  835. `M68020'
  836.      `M68020' has been observed to be predefined on some systems that
  837.      use 68020 CPUs--in addition to `mc68000' and `m68k', which are
  838.      less specific.
  839.  
  840. `_AM29K'
  841. `_AM29000'
  842.      Both `_AM29K' and `_AM29000' are predefined for the AMD 29000 CPU
  843.      family.
  844.  
  845. `ns32000'
  846.      `ns32000' is predefined on computers which use the National
  847.      Semiconductor 32000 series CPU.
  848.  
  849.    Yet other nonstandard predefined macros describe the manufacturer of
  850. the system.  For example,
  851.  
  852. `sun'
  853.      `sun' is predefined on all models of Sun computers.
  854.  
  855. `pyr'
  856.      `pyr' is predefined on all models of Pyramid computers.
  857.  
  858. `sequent'
  859.      `sequent' is predefined on all models of Sequent computers.
  860.  
  861.    These predefined symbols are not only nonstandard, they are contrary
  862. to the ANSI standard because their names do not start with underscores.
  863. Therefore, the option `-ansi' inhibits the definition of these symbols.
  864.  
  865.    This tends to make `-ansi' useless, since many programs depend on the
  866. customary nonstandard predefined symbols.  Even system header files
  867. check them and will generate incorrect declarations if they do not find
  868. the names that are expected.  You might think that the header files
  869. supplied for the Uglix computer would not need to test what machine
  870. they are running on, because they can simply assume it is the Uglix;
  871. but often they do, and they do so using the customary names.  As a
  872. result, very few C programs will compile with `-ansi'.  We intend to
  873. avoid such problems on the GNU system.
  874.  
  875.    What, then, should you do in an ANSI C program to test the type of
  876. machine it will run on?
  877.  
  878.    GNU C offers a parallel series of symbols for this purpose, whose
  879. names are made from the customary ones by adding `__' at the beginning
  880. and end.  Thus, the symbol `__vax__' would be available on a Vax, and
  881. so on.
  882.  
  883.    The set of nonstandard predefined names in the GNU C preprocessor is
  884. controlled (when `cpp' is itself compiled) by the macro
  885. `CPP_PREDEFINES', which should be a string containing `-D' options,
  886. separated by spaces.  For example, on the Sun 3, we use the following
  887. definition:
  888.  
  889.      #define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"
  890.  
  891. This macro is usually specified in `tm.h'.
  892.  
  893. File: cpp.info,  Node: Stringification,  Next: Concatenation,  Prev: Predefined,  Up: Macros
  894.  
  895. Stringification
  896. ---------------
  897.  
  898.    "Stringification" means turning a code fragment into a string
  899. constant whose contents are the text for the code fragment.  For
  900. example, stringifying `foo (z)' results in `"foo (z)"'.
  901.  
  902.    In the C preprocessor, stringification is an option available when
  903. macro arguments are substituted into the macro definition.  In the body
  904. of the definition, when an argument name appears, the character `#'
  905. before the name specifies stringification of the corresponding actual
  906. argument when it is substituted at that point in the definition.  The
  907. same argument may be substituted in other places in the definition
  908. without stringification if the argument name appears in those places
  909. with no `#'.
  910.  
  911.    Here is an example of a macro definition that uses stringification:
  912.  
  913.      #define WARN_IF(EXP) \
  914.      do { if (EXP) \
  915.              fprintf (stderr, "Warning: " #EXP "\n"); } \
  916.      while (0)
  917.  
  918. Here the actual argument for `EXP' is substituted once as given, into
  919. the `if' statement, and once as stringified, into the argument to
  920. `fprintf'.  The `do' and `while (0)' are a kludge to make it possible
  921. to write `WARN_IF (ARG);', which the resemblance of `WARN_IF' to a
  922. function would make C programmers want to do; *note Swallow
  923. Semicolon::.).
  924.  
  925.    The stringification feature is limited to transforming one macro
  926. argument into one string constant: there is no way to combine the
  927. argument with other text and then stringify it all together.  But the
  928. example above shows how an equivalent result can be obtained in ANSI
  929. Standard C using the feature that adjacent string constants are
  930. concatenated as one string constant.  The preprocessor stringifies the
  931. actual value of `EXP' into a separate string constant, resulting in
  932. text like
  933.  
  934.      do { if (x == 0) \
  935.              fprintf (stderr, "Warning: " "x == 0" "\n"); } \
  936.      while (0)
  937.  
  938. but the C compiler then sees three consecutive string constants and
  939. concatenates them into one, producing effectively
  940.  
  941.      do { if (x == 0) \
  942.              fprintf (stderr, "Warning: x == 0\n"); } \
  943.      while (0)
  944.  
  945.    Stringification in C involves more than putting doublequote
  946. characters around the fragment; it is necessary to put backslashes in
  947. front of all doublequote characters, and all backslashes in string and
  948. character constants, in order to get a valid C string constant with the
  949. proper contents.  Thus, stringifying `p = "foo\n";' results in `"p =
  950. \"foo\\n\";"'.  However, backslashes that are not inside of string or
  951. character constants are not duplicated: `\n' by itself stringifies to
  952. `"\n"'.
  953.  
  954.    Whitespace (including comments) in the text being stringified is
  955. handled according to precise rules.  All leading and trailing
  956. whitespace is ignored. Any sequence of whitespace in the middle of the
  957. text is converted to a single space in the stringified result.
  958.  
  959. File: cpp.info,  Node: Concatenation,  Next: Undefining,  Prev: Stringification,  Up: Macros
  960.  
  961. Concatenation
  962. -------------
  963.  
  964.    "Concatenation" means joining two strings into one.  In the context
  965. of macro expansion, concatenation refers to joining two lexical units
  966. into one longer one.  Specifically, an actual argument to the macro can
  967. be concatenated with another actual argument or with fixed text to
  968. produce a longer name.  The longer name might be the name of a function,
  969. variable or type, or a C keyword; it might even be the name of another
  970. macro, in which case it will be expanded.
  971.  
  972.    When you define a macro, you request concatenation with the special
  973. operator `##' in the macro body.  When the macro is called, after
  974. actual arguments are substituted, all `##' operators are deleted, and
  975. so is any whitespace next to them (including whitespace that was part
  976. of an actual argument).  The result is to concatenate the syntactic
  977. tokens on either side of the `##'.
  978.  
  979.    Consider a C program that interprets named commands.  There probably
  980. needs to be a table of commands, perhaps an array of structures
  981. declared as follows:
  982.  
  983.      struct command
  984.      {
  985.        char *name;
  986.        void (*function) ();
  987.      };
  988.      
  989.      struct command commands[] =
  990.      {
  991.        { "quit", quit_command},
  992.        { "help", help_command},
  993.        ...
  994.      };
  995.  
  996.    It would be cleaner not to have to give each command name twice,
  997. once in the string constant and once in the function name.  A macro
  998. which takes the name of a command as an argument can make this
  999. unnecessary.  The string constant can be created with stringification,
  1000. and the function name by concatenating the argument with `_command'. 
  1001. Here is how it is done:
  1002.  
  1003.      #define COMMAND(NAME)  { #NAME, NAME ## _command }
  1004.      
  1005.      struct command commands[] =
  1006.      {
  1007.        COMMAND (quit),
  1008.        COMMAND (help),
  1009.        ...
  1010.      };
  1011.  
  1012.    The usual case of concatenation is concatenating two names (or a
  1013. name and a number) into a longer name.  But this isn't the only valid
  1014. case.  It is also possible to concatenate two numbers (or a number and
  1015. a name, such as `1.5' and `e3') into a number.  Also, multi-character
  1016. operators such as `+=' can be formed by concatenation.  In some cases
  1017. it is even possible to piece together a string constant.  However, two
  1018. pieces of text that don't together form a valid lexical unit cannot be
  1019. concatenated.  For example, concatenation with `x' on one side and `+'
  1020. on the other is not meaningful because those two characters can't fit
  1021. together in any lexical unit of C.  The ANSI standard says that such
  1022. attempts at concatenation are undefined, but in the GNU C preprocessor
  1023. it is well defined: it puts the `x' and `+' side by side with no
  1024. particular special results.
  1025.  
  1026.    Keep in mind that the C preprocessor converts comments to whitespace
  1027. before macros are even considered.  Therefore, you cannot create a
  1028. comment by concatenating `/' and `*': the `/*' sequence that starts a
  1029. comment is not a lexical unit, but rather the beginning of a "long"
  1030. space character.  Also, you can freely use comments next to a `##' in a
  1031. macro definition, or in actual arguments that will be concatenated,
  1032. because the comments will be converted to spaces at first sight, and
  1033. concatenation will later discard the spaces.
  1034.  
  1035. File: cpp.info,  Node: Undefining,  Next: Redefining,  Prev: Concatenation,  Up: Macros
  1036.  
  1037. Undefining Macros
  1038. -----------------
  1039.  
  1040.    To "undefine" a macro means to cancel its definition.  This is done
  1041. with the `#undef' command.  `#undef' is followed by the macro name to
  1042. be undefined.
  1043.  
  1044.    Like definition, undefinition occurs at a specific point in the
  1045. source file, and it applies starting from that point.  The name ceases
  1046. to be a macro name, and from that point on it is treated by the
  1047. preprocessor as if it had never been a macro name.
  1048.  
  1049.    For example,
  1050.  
  1051.      #define FOO 4
  1052.      x = FOO;
  1053.      #undef FOO
  1054.      x = FOO;
  1055.  
  1056. expands into
  1057.  
  1058.      x = 4;
  1059.      
  1060.      x = FOO;
  1061.  
  1062. In this example, `FOO' had better be a variable or function as well as
  1063. (temporarily) a macro, in order for the result of the expansion to be
  1064. valid C code.
  1065.  
  1066.    The same form of `#undef' command will cancel definitions with
  1067. arguments or definitions that don't expect arguments.  The `#undef'
  1068. command has no effect when used on a name not currently defined as a
  1069. macro.
  1070.  
  1071. File: cpp.info,  Node: Redefining,  Next: Macro Pitfalls,  Prev: Undefining,  Up: Macros
  1072.  
  1073. Redefining Macros
  1074. -----------------
  1075.  
  1076.    "Redefining" a macro means defining (with `#define') a name that is
  1077. already defined as a macro.
  1078.  
  1079.    A redefinition is trivial if the new definition is transparently
  1080. identical to the old one.  You probably wouldn't deliberately write a
  1081. trivial redefinition, but they can happen automatically when a header
  1082. file is included more than once (*note Header Files::.), so they are
  1083. accepted silently and without effect.
  1084.  
  1085.    Nontrivial redefinition is considered likely to be an error, so it
  1086. provokes a warning message from the preprocessor.  However, sometimes it
  1087. is useful to change the definition of a macro in mid-compilation.  You
  1088. can inhibit the warning by undefining the macro with `#undef' before the
  1089. second definition.
  1090.  
  1091.    In order for a redefinition to be trivial, the new definition must
  1092. exactly match the one already in effect, with two possible exceptions:
  1093.  
  1094.    * Whitespace may be added or deleted at the beginning or the end.
  1095.  
  1096.    * Whitespace may be changed in the middle (but not inside strings).
  1097.      However, it may not be eliminated entirely, and it may not be added
  1098.      where there was no whitespace at all.
  1099.  
  1100.    Recall that a comment counts as whitespace.
  1101.  
  1102. File: cpp.info,  Node: Macro Pitfalls,  Prev: Redefining,  Up: Macros
  1103.  
  1104. Pitfalls and Subtleties of Macros
  1105. ---------------------------------
  1106.  
  1107.    In this section we describe some special rules that apply to macros
  1108. and macro expansion, and point out certain cases in which the rules have
  1109. counterintuitive consequences that you must watch out for.
  1110.  
  1111. * Menu:
  1112.  
  1113. * Misnesting::        Macros can contain unmatched parentheses.
  1114. * Macro Parentheses:: Why apparently superfluous parentheses
  1115.                          may be necessary to avoid incorrect grouping.
  1116. * Swallow Semicolon:: Macros that look like functions
  1117.                          but expand into compound statements.
  1118. * Side Effects::      Unsafe macros that cause trouble when
  1119.                          arguments contain side effects.
  1120. * Self-Reference::    Macros whose definitions use the macros' own names.
  1121. * Argument Prescan::  Actual arguments are checked for macro calls
  1122.                          before they are substituted.
  1123. * Cascaded Macros::   Macros whose definitions use other macros.
  1124. * Newlines in Args::  Sometimes line numbers get confused.
  1125.  
  1126. File: cpp.info,  Node: Misnesting,  Next: Macro Parentheses,  Prev: Macro Pitfalls,  Up: Macro Pitfalls
  1127.  
  1128. Improperly Nested Constructs
  1129. ............................
  1130.  
  1131.    Recall that when a macro is called with arguments, the arguments are
  1132. substituted into the macro body and the result is checked, together with
  1133. the rest of the input file, for more macro calls.
  1134.  
  1135.    It is possible to piece together a macro call coming partially from
  1136. the macro body and partially from the actual arguments.  For example,
  1137.  
  1138.      #define double(x) (2*(x))
  1139.      #define call_with_1(x) x(1)
  1140.  
  1141. would expand `call_with_1 (double)' into `(2*(1))'.
  1142.  
  1143.    Macro definitions do not have to have balanced parentheses.  By
  1144. writing an unbalanced open parenthesis in a macro body, it is possible
  1145. to create a macro call that begins inside the macro body but ends
  1146. outside of it.  For example,
  1147.  
  1148.      #define strange(file) fprintf (file, "%s %d",
  1149.      ...
  1150.      strange(stderr) p, 35)
  1151.  
  1152. This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
  1153.  
  1154. File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
  1155.  
  1156. Unintended Grouping of Arithmetic
  1157. .................................
  1158.  
  1159.    You may have noticed that in most of the macro definition examples
  1160. shown above, each occurrence of a macro argument name had parentheses
  1161. around it. In addition, another pair of parentheses usually surround
  1162. the entire macro definition.  Here is why it is best to write macros
  1163. that way.
  1164.  
  1165.    Suppose you define a macro as follows,
  1166.  
  1167.      #define ceil_div(x, y) (x + y - 1) / y
  1168.  
  1169. whose purpose is to divide, rounding up.  (One use for this operation is
  1170. to compute how many `int' objects are needed to hold a certain number
  1171. of `char' objects.)  Then suppose it is used as follows:
  1172.  
  1173.      a = ceil_div (b & c, sizeof (int));
  1174.  
  1175. This expands into
  1176.  
  1177.      a = (b & c + sizeof (int) - 1) / sizeof (int);
  1178.  
  1179. which does not do what is intended.  The operator-precedence rules of C
  1180. make it equivalent to this:
  1181.  
  1182.      a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  1183.  
  1184. But what we want is this:
  1185.  
  1186.      a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  1187.  
  1188. Defining the macro as
  1189.  
  1190.      #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  1191.  
  1192. provides the desired result.
  1193.  
  1194.    However, unintended grouping can result in another way.  Consider
  1195. `sizeof ceil_div(1, 2)'.  That has the appearance of a C expression
  1196. that would compute the size of the type of `ceil_div (1, 2)', but in
  1197. fact it means something very different.  Here is what it expands to:
  1198.  
  1199.      sizeof ((1) + (2) - 1) / (2)
  1200.  
  1201. This would take the size of an integer and divide it by two.  The
  1202. precedence rules have put the division outside the `sizeof' when it was
  1203. intended to be inside.
  1204.  
  1205.    Parentheses around the entire macro definition can prevent such
  1206. problems. Here, then, is the recommended way to define `ceil_div':
  1207.  
  1208.      #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  1209.  
  1210. ə